package com.ht.shop.dao.impl;

import com.ht.shop.dao.AddressDao;
import com.ht.shop.pojo.TbAddress;
import com.ht.shop.utils.DBUtils;
import com.ht.shop.utils.SqlUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AddressDaoImpl implements AddressDao {
    private QueryRunner queryRunner =new QueryRunner(DBUtils.getSource());
    @Override
    public List<TbAddress> findAllAddressByUid(long uid) {
        String sql = SqlUtils.getSql("address.selectbyuid");
        try {
            List<TbAddress> addressList = queryRunner.query(sql, new BeanListHandler<>(TbAddress.class), uid);
            return addressList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public long addAddress(String detail, String name, String phone,long uid) {
        String sql = SqlUtils.getSql("address.add");
        try {
            Long insert = queryRunner.insert(sql, new ScalarHandler<>(),detail,name,phone,uid);
            return insert;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public long updateAddress(String detail, String name, String phone, long id) {
        String sql = SqlUtils.getSql("address.update");
        try {
            int update = queryRunner.update(sql, detail, name, phone, id);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public void deleteAddressById(long id) {
        String sql = SqlUtils.getSql("address.delete");
        try {
            queryRunner.update(sql,id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<TbAddress> findAllAddressById() throws Exception {
        String sql = SqlUtils.getSql("address.findall");
        List<TbAddress> tbAddressList = queryRunner.query(sql, new BeanListHandler<>(TbAddress.class));

        return tbAddressList;
    }


}
